package com.pubinfo.passbook.api.controller.engine;

import com.pubinfo.passbook.common.entity.TEngineComputeUnit;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.model.dto.engine.EngineUnitParam;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.base.MyPage;
import com.pubinfo.passbook.common.service.engine.EngineComputeUnitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author zhouch
 * @date 2021/12/20 16:46
 */
@Api(tags = "计算引擎-计算单元管理")
@RestController
@RequestMapping("/engine/unit")
public class EngineUnitController {

    @Resource
    EngineComputeUnitService unitService;

    @PostMapping("/page")
    @ApiOperation("分页查询")
    public JsonResult<MyPage<TEngineComputeUnit>> page(@RequestBody @Valid EngineUnitParam param) {
        return JsonResult.page(unitService.page(param));
    }

    @PostMapping("/save")
    @ApiOperation("保存")
    public JsonResult<Boolean> save(@RequestBody @Valid TEngineComputeUnit unitInfo) {
        if (unitInfo.getId() != null) {
            throw new ServiceException("ID字段存在");
        }

        if (unitService.existSymbol(unitInfo.getSymbol())) {
            throw new ServiceException("标识符已经存在了.");
        }

        return JsonResult.success(unitService.save(unitInfo));
    }

    @PostMapping("/update")
    @ApiOperation("更新")
    public JsonResult<Boolean> update(@RequestBody @Valid TEngineComputeUnit unitInfo) {
        if (unitInfo.getId() == null) {
            throw new ServiceException("ID字段不存在");
        }

        if (unitService.existSymbol(unitInfo.getSymbol())) {
            // 如果 Symbol 已经存在, 并且
            if (!unitService.getBySymbol(unitInfo.getSymbol()).getId().equals(unitInfo.getId())) {
                throw new ServiceException("标识符已经存在了, 无法修改.");
            }
        }

        return JsonResult.success(unitService.updateById(unitInfo));
    }

    @GetMapping("/remove/{id}")
    @ApiOperation("删除")
    public JsonResult<Boolean> remove(@PathVariable("id") Integer id) {
        return JsonResult.success(unitService.removeById(id));
    }


    @GetMapping("/get/{id}")
    @ApiOperation("详情")
    public JsonResult<TEngineComputeUnit> get(@PathVariable("id") Integer id) {
        return JsonResult.success(unitService.getById(id));
    }
}
